package com.thientan.controller

import grails.converters.JSON

import com.thientan.model.DuLieuHeThong
import com.thientan.model.enums.LoaiDuLieu
import com.thientan.service.DuLieuService

class DuLieuController extends AbstractBaseController {

	DuLieuService duLieuService
	@Override
	public Class getDomainClass() {
		DuLieuHeThong.class
	}

	@Override
	public Object getDomainService() {
		duLieuService
	}

	@Override
	public String getDomainName() {
		message(code : "default.thientan.messages.duLieu")
	}

	@Override
	public String getDisplayFieldName() {
		'giaTri'
	}

	def initData = {
		List dataTypes = LoaiDuLieu.values().collect {
			["value" : it.name(), "text" : it.displayText]
		}
		List cities = DuLieuHeThong.findAllByLoaiDuLieu(LoaiDuLieu.TINH_THANH)
		Map result = ["dataTypes" : dataTypes, "cities" : extractPropertiesAsMaps(cities, ["maDuLieu", "giaTri"])]
		render result as JSON
	}

	def reloadRelatedData = {
		String selectedDataType = params['dataType']
		LoaiDuLieu type
		if(selectedDataType == LoaiDuLieu.PHUONG_XA.name()) {
			type = LoaiDuLieu.QUAN_HUYEN
		} else if(selectedDataType == LoaiDuLieu.QUAN_HUYEN.name()) {
			type = LoaiDuLieu.TINH_THANH
		}

		List result = DuLieuHeThong.withCriteria {
			projections {
				property("maDuLieu")
				property("giaTri")
			}
			eq("loaiDuLieu", type)
		}.collect {
			["value" : it[0], "text" : it[1]]
		}
		render result as JSON
	}
	
	Map prepareParams() {
		Map parameters = params
		parameters.putAt("maDuLieu", params["maDuLieu"].toUpperCase())
		parameters.putAt("loaiDuLieu", LoaiDuLieu.valueOf(params["loaiDuLieu"]))
		return parameters
	}
	
	def validateCode = {
		String code = params["code"]
		Map result = ['codeExist' : DuLieuHeThong.countByMaDuLieu(code) > 0]
		render result as JSON
	}
}
